package com.smartlbs.quartz;
import com.smartlbs.service.IGameInfoService;
import com.smartlbs.service.ISettingService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;

import javax.annotation.PostConstruct;
import java.util.Map;
@Component("QuartzJob")
public class QuartzJob implements Job {
	@Qualifier("IGameInfoService")
	@Autowired
	private IGameInfoService gameInfoService;
	@Autowired
	private ISettingService settingService;
	@Autowired
	private QuartzMangerService quartz;
	@Override
	public void execute(JobExecutionContext arg0) throws JobExecutionException {
		SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);

		// TODO Auto-generated method stub
		try {
			gameInfoService.insertChamps();
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}	
	@PostConstruct
	public void initquartz(){
		Map<String, String> setting = settingService.getSetting("3");
		Integer time = null;
		String cron = "0 0 0/1 * * ? ";
		Integer hours = null;
		if(setting!=null){
			 time = Integer.valueOf(setting.get("time"));
			 if (time < 60) {
					cron = "0 0/" + time + " * * * ?";
				} else {
					if(time%60<30){
						hours = time / 60;
					}else {
						hours=time/60+1;
					}
					cron = "0 0 0/" + hours + " * * ? ";
				}
		}	

		String jobName = "jobName";
		String jobGroupName = "jobGroupName";
		String triggerName = "triggerName";
		String triggerGroupName = "triggerGroupName";

		// 移除一个定时任务
		quartz.removeJob(jobName, jobGroupName, triggerName,
				triggerGroupName);
		// 开启一个默认的定时任务
		quartz.addJob(jobName, jobGroupName, triggerName, triggerGroupName,
				QuartzJob.class, cron, null);
		settingService.setting(3, String.valueOf(time));
		

	}

}
